import iButton from '@/components/carGoods/i-button.vue'

export default {
  components: { iButton },
  data() {
    return {
      addressShow: false, // 收显示货地址列表弹框
      radioAddress: 0, // 控制单选收货地址
      addressList: [], // 收货地址列表
      addressData: {}, // 选择用于显示的地址
      storeName: '', // 当前用户店铺名称

      tagStatus: 'buy', // 入口标识，buyCar: 购物车，buy: 详情页点击立即购买
      carGoodsDetailInfo: {}, // 详情页面或者购物车带过来的参数
      detailData: {}, // 车品信息
      isinvoice: false, // 是否开发票
      invoicePopupShow: false, // 显示选择发票弹框
    }
  },

  onLoad(e) {
    // 车品id和数量
    this.carGoodsDetailInfo = JSON.parse(e.data)
    this.tagStatus = e.tag

    uni.$on('addressChange', res => {
      this.getAddressList()
    })
    // this.type = e.type
  },

  created() {
    this.storeName = uni.getStorageSync('userInfoDetail').store.storeName
    this.getAddressList()
    this.tagStatus === 'buy'
      ? this.getCarGoodsInfo()
      : this.getCarGoodsInfoBuyCar()
  },

  methods: {
    // 获取收货地址
    async getAddressList() {
      uni.showLoading()
      try {
        let data = {
          PageIndex: 1,
          PageSize: 100,
        }
        const res = await this.$api.common.addressList(data)
        if (res.data.list.length !== 0) {
          this.addressList = res.data.list.map(item => ({
            ...item,
            addressAll: item.mcprovince + item.mccity + item.mcdistrict + item.address,
          }))
          this.addressData = this.addressList[0] || null
          console.log(res.data)
        } else {
          this.addressList = res.data.list
        }
      } catch (e) {
        console.log(e)
      }
      uni.hideLoading()
    },

    // 获取车品详情信息 - 从车品详情进来，请求此接口
    async getCarGoodsInfo() {
      uni.showLoading()
      try {
        const res = await this.$api.carGoodsOrder.OrderCarSuppliesAffirm({
          buyer_storeid: uni.getStorageSync('userInfoDetail').store.storeId,
          storelist: [
            {
              seller_storeid: this.carGoodsDetailInfo.storeData.id,
              list: [
                {
                  car_supplie_id: this.carGoodsDetailInfo.id,
                  count: this.carGoodsDetailInfo.count,
                },
              ],
            },
          ],
        })
        res.data.storelist.forEach(item => {
          item.remark = ''
        })
        this.detailData = res.data
        console.log('提交订单数据详情', res.data)
      } catch (err) {
        //
      }
      uni.hideLoading()
    },

    // 获取车品详情信息 - 从购物车进来，请求此接口
    async getCarGoodsInfoBuyCar() {
      uni.showLoading()
      try {
        const res = await this.$api.carGoodsOrder.OrderCarSuppliesAffirmBuyCar({
          list: this.carGoodsDetailInfo,
        })
        res.data.storelist.forEach(item => {
          item.remark = ''
        })
        this.detailData = res.data
        console.log('提交订单数据详情', res.data)
      } catch (err) {
        //
      }
      uni.hideLoading()
    },

    // 单选地址。选中地址
    checkedAddress(index) {
      this.radioAddress = index
      this.addressData = this.addressList[index]
      this.addressShow = false
    },

    // 跳转新增/编辑地址页面
    goAddressPage(data, type) {
      let urls = {
        add: '/pages_common/newAddress/newAddress',
        edit: `/pages_common/editAddress/editAddress?addressid=${JSON.stringify(
          data
        )}`,
      }
      uni.navigateTo({
        url: urls[type],
      })
    },

    // 选择是否开具发票
    selectedInvoice(flag) {
      this.isinvoice = flag
      this.invoicePopupShow = !this.invoicePopupShow
    },

    // 点击店铺，跳转到店铺主页
    goStorePage(id) {
      uni.navigateTo({
        url: '/pages_common/store/store?id=' + id
      })
    },

    // 点击商品，跳转到商品详情 - 车品
    goGoodsPage(data) {
      uni.navigateTo({
        url: '/pages_carGoods/carGoodsDetail/carGoodsDetail?id=' + data.car_supplies_id
      })
    },

    // 提交订单
    async submitOrder() {
      if (!this.addressData.addressAll) {
        uni.showToast({
          title: '请选择收货地址',
          icon: 'none'
        })
        return false
      }

      let storeList = []
      this.detailData.storelist.forEach(s => {
        storeList.push({
          goodlist: s.goodlist.map(goods => ({
            car_supplies_id: goods.car_supplies_id,
            count: goods.count,
          })),
          store_id: s.store_id,
          store_name: s.store_name,
          freight: Number(s.freight) || 0,
          isinvoice: this.isinvoice, // 是否开发票
          remark: s.remark,
        })
      })
      let data = {
        receiver_name: this.addressData.name,
        receiver_phone: this.addressData.mobile,
        receiver_address: this.addressData.addressAll,
        storeList,
        isshopping_trolley: this.tagStatus === 'buyCar'
      }
      console.log(data)

      uni.showLoading({
        title: '正在提交',
      })
      try {
        const res = await this.$api.carGoodsOrder.OrderCarSuppliesCreate(data)
        uni.showToast({ title: '提交成功' })
        console.log('提交成功，待付款', res)
        let orderNo = res.data.id

        uni.redirectTo({
          url: `/pages_order/pay/pay?orderNo=${orderNo}&price=${this.detailData.total_money}&type=carGoods`,
        })
      } catch (err) {
        console.log(err)
      }
      uni.hideLoading()
    },
  },
}
